package com.mediacloud.app.newsmodule.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mediacloud.app.model.OnVideoPause;
import com.mediacloud.app.model.OnVideoPlayerPause;
import com.mediacloud.app.model.OnVideoPlayerPause2;
import com.google.android.factory2.view.layoutInflate.InflateFactory2;
import com.mediacloud.app.cloud.ijkplayersdk.video.MultiUtils;
import com.mediacloud.app.cloud.ijkplayersdk.video.MultiVideoMannager;
import com.mediacloud.app.cloud.ijkplayersdk.video.MultiVideoPlayer;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.nav2.fragment.ICMP26Holder;
import com.mediacloud.app.newsmodule.adaptor.component.ComponentListItemStyleAdaptor;
import com.mediacloud.app.newsmodule.adaptor.component.Component13Holder;
import com.mediacloud.app.newsmodule.broadcast.AudioBackgroundBroad;
import com.mediacloud.app.newsmodule.fragment.video.vod.PlayClickListener;
import com.mediacloud.app.newsmodule.interfaces.ComponentParent;
import com.mediacloud.app.newsmodule.interfaces.OnSmallVideoPlayListner;

import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 组件窗口
 *
 * @author x
 */
public class ComponentContainer extends FrameLayout implements ComponentParent, Runnable, OnSmallVideoPlayListner, DefaultLifecycleObserver {
    public ComponentListItemStyleAdaptor componentListItemStyleAdaptor;
      public PlayClickListener playClickListener=null;
    Context context;
   // Handler handler = new MsgHandle(Looper.getMainLooper());
    protected boolean isDisposed = false;
    Component13Holder mSmallVideoHolder;
    public MultiVideoPlayer mMultiVideoPlayer;

    public PlayClickListener getPlayClickListener() {
        return playClickListener;
    }

    public void setPlayClickListener(PlayClickListener playClickListener) {
        this.playClickListener = playClickListener;
    }

    protected SparseArray<View> insertView = new SparseArray<View>();
    @Override
    public boolean isFirstAdd() {
        return isFirstAdd;
    }

    boolean isFirstAdd = true;
    int scrennH = 0;

    final String TAG = "ComponentContainer";
    private ICMP26Holder  icmp26Holder;
    public ComponentContainer(Context context,ICMP26Holder  icmp26Holder) {
        super(context);
        this.icmp26Holder =icmp26Holder;
        init(context);
    }
    public ComponentContainer(Context context) {
        super(context);
        init(context);
    }

    boolean isWindow = false;

    protected final void sendHideFloaWinMsg() {
        Intent intent = new Intent();
        intent.setAction(AudioBackgroundBroad.HideAction);
        LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
    }

    protected void stopPlay() {
//        Intent intent = new Intent();
//        intent.putExtra(AudioConst.Action, AudioConst.ChangeLine);
//        intent.setClass(getContext(), AudioVodPlayService.class);
//        getContext().startService(intent);
        KillMusicUtils.stopAPS(context);
    }

    @Override
    public void onPlays(String url, Component13Holder holder, String title) {

//        if(url.equals("")) {
//            url = "http://dianbo02.jxtvcn.com.cn/jxwlgbdst/vod/2017/04/10/8f637652b77549be99ed2e86aa654c69/h264_800k_mp4.mp4";
//        }
    /*    Bitmap map= BitmapUtil.convertViewToBitmap(this);
        BitmapUtil.saveMyBitmap(map,"test");*/
        sendHideFloaWinMsg();
        stopPlay();
        if (mMultiVideoPlayer == null) {
            mMultiVideoPlayer = new MultiVideoPlayer(getContext());
            mMultiVideoPlayer.setPoster(url, AppFactoryGlobalConfig.getDefaultImageLoadDrawable(),AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.img_cut);
            mMultiVideoPlayer.setIsLive(true);
            initPlayer();
        }
     /*   if (mMultiVideoPlayer.isWindow && isWindow) {
            isWindow = false;
            mMultiVideoPlayer.outtWindow();
            ViewGroup vp = (ViewGroup) mMultiVideoPlayer.getParent();
            vp.removeView(mMultiVideoPlayer);
            mMultiVideoPlayer.outWindow();
           // mSmallVideoHolder.startThisPlay(mMultiVideoPlayer);
        }*/
        stopWindows();
        stopUpSmallVideoUi();
        MultiVideoMannager.getInstace().setIsPlay(true);
        if (holder != mSmallVideoHolder) {

            if (mSmallVideoHolder != null)
                mSmallVideoHolder.updateNumUi();
        }
        mMultiVideoPlayer.setUrl(url);
        mMultiVideoPlayer.setPoster(url, AppFactoryGlobalConfig.getDefaultImageLoadDrawable(),AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.img_cut);
        mTitle = title;
        mMultiVideoPlayer.setTitle(title);
        mSmallVideoHolder = holder;
        mSmallVideoHolder.startThisPlay(mMultiVideoPlayer);
        mMultiVideoPlayer.playNews();
        EventBus.getDefault().post(new OnVideoPause());
        EventBus.getDefault().post(new OnVideoPlayerPause2());
    }

    String mTitle = "";

    private void initPlayer() {

        scrennH = getWindowInfo(false);
        mMultiVideoPlayer.setOnViewChangeListner(new MultiVideoPlayer.OnViewChangeListner() {

            @Override
            public void onRemove() {

                chageView();
            }

            @Override
            public void onChange() {
                if (mMultiVideoPlayer.isPause && mMultiVideoPlayer.isWindow) {
                    stopWindows();
                    stopUpSmallVideoUi();
                    return;
                }
                RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                layoutParams1.addRule(RelativeLayout.CENTER_IN_PARENT);
                mMultiVideoPlayer.setVisibility(View.GONE);
                if (mMultiVideoPlayer.getParent() != null) {
                    ((ViewGroup) mMultiVideoPlayer.getParent()).removeView(mMultiVideoPlayer);
                    mMultiVideoPlayer = null;
                }
                mMultiVideoPlayer = new MultiVideoPlayer(getContext());
                mMultiVideoPlayer.setIsLive(true);
                mMultiVideoPlayer.setTitle(mTitle);
                mMultiVideoPlayer.setIsNewView();
                mSmallVideoHolder.startThisPlay(mMultiVideoPlayer);

                initPlayer();

            }
        });
        mMultiVideoPlayer.setOnWindowCloseListner(new MultiVideoPlayer.OnWindowCloseListner() {
            @Override
            public void onClose() {
                isWindow = false;
                chageView();
                mSmallVideoHolder = null;
            }
        });

    }

    public void stopWindows() {
        if (mMultiVideoPlayer != null && mMultiVideoPlayer.isWindow && isWindow) {
            isWindow = false;
            mMultiVideoPlayer.outtWindow();
            ViewGroup vp = (ViewGroup) mMultiVideoPlayer.getParent();
            vp.removeView(mMultiVideoPlayer);
            mMultiVideoPlayer.outWindow();
            // mSmallVideoHolder.startThisPlay(mMultiVideoPlayer);
        }
    }

    public void stopUpSmallVideoUi() {
        if (mSmallVideoHolder != null) {
            mMultiVideoPlayer.stopPlay();
            mSmallVideoHolder.stopThisPlay();
        }
    }

    View mRootView;

    public void setRootView(View rootView) {
        mRootView = rootView;
    }

    private void chageView() {

        if (mSmallVideoHolder != null) {
            mSmallVideoHolder.stopThisPlay();

        }
    }

    public void setRecyclerView(final RecyclerView recyclerView) {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int[] xy = new int[2];
                recyclerView.getLocationOnScreen(xy);
                if (null != mSmallVideoHolder && null != mMultiVideoPlayer && !mMultiVideoPlayer.isExchangeToFull) {
                    int[] location = new int[2];
                    mSmallVideoHolder.players.getLocationOnScreen(location);
                    int x = location[0];
                    int y = location[1];
                    int vh = mSmallVideoHolder.players.getHeight();

                    int[] rootxy = new int[2];
                    mRootView.getLocationOnScreen(rootxy);
                    boolean isOut = (0 - (vh - xy[1])) > y || y > (rootxy[1] + mRootView.getHeight());
                    if (mMultiVideoPlayer.isWindow && y == 0) {
                        isOut = true;
                    }
                    if (isOut) {
                        if (!mMultiVideoPlayer.isWindow && (mMultiVideoPlayer.isPlaying() || mMultiVideoPlayer.isPause)) {

                            if (mMultiVideoPlayer.isPause) {
                                stopUpSmallVideoUi();
                                return;
                            }
                            chageView();
                            mMultiVideoPlayer.startWindow(mMultiVideoPlayer);
                            isWindow = true;
                        }
                    } else {

                        if (mMultiVideoPlayer.isWindow && isWindow) {
                            isWindow = false;
                            mMultiVideoPlayer.outtWindow();
                            ViewGroup vp = (ViewGroup) mMultiVideoPlayer.getParent();
                            vp.removeView(mMultiVideoPlayer);
                            mMultiVideoPlayer.outWindow();
                            mSmallVideoHolder.startThisPlay(mMultiVideoPlayer);
                        }
                    }
                }


            }
        });
    }

    public void setmListView(final AbsListView listView) {

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (mSmallVideoHolder != null) {
                }
                //listView在屏幕上的位置
                int[] xy = new int[2];
                listView.getLocationOnScreen(xy);
                // mMultiVideoPlayer.isExchangeToFull true全屏状态
                if (null != mSmallVideoHolder && null != mMultiVideoPlayer && !mMultiVideoPlayer.isExchangeToFull) {
                    //播放器在屏幕上的位置
                    int[] location = new int[2];
                    mSmallVideoHolder.players.getLocationOnScreen(location);
                    int x = location[0];
                    int y = location[1];
                    int vh = mSmallVideoHolder.players.getHeight();

                    //应该是根布局在屏幕上的位置
                    int[] rootxy = new int[2];
                    mRootView.getLocationOnScreen(rootxy);
                    boolean isOut = (0 - (vh - xy[1])) > y || y > (rootxy[1] + mRootView.getHeight());
                    if (mMultiVideoPlayer.isWindow && y == 0) {
                        isOut = true;
                    }
                    if (isOut) {
                        if (!mMultiVideoPlayer.isWindow && (mMultiVideoPlayer.isPlaying() || mMultiVideoPlayer.isPause)) {

                            if (mMultiVideoPlayer.isPause) {
                                stopUpSmallVideoUi();
                                return;
                            }
                            chageView();
                            mMultiVideoPlayer.startWindow(mMultiVideoPlayer);
                            isWindow = true;
                        }
                    } else {

                        if (mMultiVideoPlayer.isWindow && isWindow) {
                            isWindow = false;
                            mMultiVideoPlayer.outtWindow();
                            ViewGroup vp = (ViewGroup) mMultiVideoPlayer.getParent();
                            vp.removeView(mMultiVideoPlayer);
                            mMultiVideoPlayer.outWindow();
                            mSmallVideoHolder.startThisPlay(mMultiVideoPlayer);
                        }
                    }
                }


            }
        });

    }

    public static boolean isFullScreen(Activity activity) {
        int flag = activity.getWindow().getAttributes().flags;
        return (flag & WindowManager.LayoutParams.FLAG_FULLSCREEN)
                == WindowManager.LayoutParams.FLAG_FULLSCREEN;
    }

    public ComponentContainer(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ComponentContainer(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    protected void init(Context context) {
        this.context = context;
        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
        componentListItemStyleAdaptor = new ComponentListItemStyleAdaptor(context);
        componentListItemStyleAdaptor.setOnSmallVideoPlayListner(this);
        setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoPause(OnVideoPlayerPause pause) {
        if (context==null){
            return;
        }
        if (context instanceof Activity){
            if(((Activity)context).isFinishing()||((Activity)context).isDestroyed()){
                return;
            }
        }
        if (mMultiVideoPlayer != null) {
            //20200430修改bug，在别的视频播放时，发出一个通知，让这个直播暂停并关闭掉小窗
            MultiVideoMannager.getInstace().isHandPause = true;
            mMultiVideoPlayer.onPause();
            stopWindows();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoPause(OnVideoPause pause) {
        if (context==null){
            return;
        }
        if (context instanceof Activity){
            if(((Activity)context).isFinishing()||((Activity)context).isDestroyed()){
                return;
            }
        }
        if (mMultiVideoPlayer != null) {
            //20200430修改bug，在别的视频播放时，发出一个通知，让这个直播暂停并关闭掉小窗
            MultiVideoMannager.getInstace().isHandPause = true;
            mMultiVideoPlayer.onPause();
            stopWindows();
        }
    }
    ArrayList<ComponentItem> componentItems;
    //用于更改主题后的刷新
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void refresh(){
        if(componentItems!=null){
            updateComponent(componentItems);
        }
    }
    String oldMd5="";
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public synchronized void updateComponent(final ArrayList<ComponentItem> componentItems) {
      StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < componentItems.size(); i++) {
            stringBuffer.append(componentItems.get(i).getOrginData());
        }
//      String md5 =  MD5Util.MD5Encode(stringBuffer.toString(),"UTF-8");
//        if(oldMd5.equals(md5)){
//           Log.w("YOAKE","组件数据没变。不刷新界面");
//            return;
//        }
//        oldMd5 =md5;
        if(icmp26Holder!=null){
            icmp26Holder.removeCMP26Flag();
        }
        this.componentItems =componentItems;
        oldContainer = lastedContainer;
        if (oldContainer != null) {
            oldContainer.setContentDescription("oldContainer");
        }
        lastedContainer = null;
        if (isFirstAdd) {
            showView(componentItems, false);
            isFirstAdd = false;
        } else {
            refreshData(componentItems, false);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void refreshData(List<ComponentItem> componentItems, boolean addInsert) {
        showView(componentItems, addInsert);
        if (addInsert) {
            Log.w(TAG, "handleMessage addInsert");
        } else {
            Log.w(TAG, "handleMessage update");
        }
        if (!addInsert) {
            removeOldContainer();
            Log.w(TAG, "send clear all compponent msg");
        } else {
            run();
        }
    }

    public void removeOldContainer() {
        Log.w(TAG, "clear oldContainer");
        if (oldContainer != null) {
            oldContainer.removeAllViews();
            if (oldContainer.getParent() != null) {
                ((ViewGroup) oldContainer.getParent()).removeView(oldContainer);
            }
        }
        oldContainer = null;
        int ChildCount = getChildCount();
        Log.w(TAG, "clear all compponent complete ChildCount>>" + ChildCount);
        if (ChildCount > 0) {
            Log.w(TAG, "child hashCode>>" + getChildAt(0).hashCode());
        }
    }


    public void remove2() {
        if (lastedContainer != null)
            lastedContainer.removeAllViews();
    }

    public void clearOld() {
        oldContainer = lastedContainer;
        if (oldContainer != null) {
            oldContainer.setContentDescription("oldContainer");
        }
        lastedContainer = null;
        removeOldContainer();
    }

    final int delay = 333;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public synchronized void insertComponent(final ArrayList<ComponentItem> componentItems) {
        refreshData(componentItems,true);
    }

    public synchronized void clearInsertComponent() {
        Log.w(TAG, "clearInsertComponent:" + insertView.size());
        for (int index = 0; index < insertView.size(); index++) {
            View view = insertView.get(index);
            if (view.getParent() != null) {
                ((ViewGroup) view.getParent()).removeView(view);
            }
        }
        insertView.clear();
//        removeFactory2();
    }


    void removeFactory2() {
        Activity activity = (Activity) getContext();
        if (activity != null && activity.getLayoutInflater() != null && activity.getLayoutInflater().getFactory2() instanceof InflateFactory2) {
            ((InflateFactory2) activity.getLayoutInflater().getFactory2()).removeDestoryView();
        }
    }

    LinearLayoutCompat lastedContainer;
    LinearLayoutCompat oldContainer;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    protected void showView(List<ComponentItem> componentItems, boolean addInsert) {
        if (isDisposed)
            return;
        componentListItemStyleAdaptor.setPlayClickListener(playClickListener);
        componentListItemStyleAdaptor.setListContentData(componentItems);
        if (lastedContainer == null) {
            lastedContainer = new LinearLayoutCompat(getContext());
           // lastedContainer.setBackgroundColor(Color.WHITE);
            lastedContainer.setOrientation(LinearLayoutCompat.VERTICAL);
            lastedContainer.setContentDescription("lastedContainer");
        }
        componentListItemStyleAdaptor.clearEvent();
        for (int index = 0; index < componentItems.size(); index++) {
            if (componentItems.get(0).widget == TypeX.COMPONENT.C999936){//置顶组件背景透明
                 lastedContainer.setBackgroundColor(Color.TRANSPARENT);
            }else  lastedContainer.setBackgroundColor(Color.WHITE);
            View view = componentListItemStyleAdaptor.getView(index, null, this);
            if (view == null)
                continue;
            view.setContentDescription(componentItems.get(index).getTitle() + componentItems.get(index).getName());
            if (addInsert) {
                insertView.put(index, view);
            }
            lastedContainer.addView(view);
        }
        if (lastedContainer.getParent() == null) {
            addView(lastedContainer, 0);
        }
    }

    public void dispose() {
        isDisposed = true;
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
        context=null;
        if (mMultiVideoPlayer!=null){
            mMultiVideoPlayer.stopPlay();
            mMultiVideoPlayer=null;
        }
        if (mSmallVideoHolder!=null){
            mSmallVideoHolder=null;
        }
        mRootView = null;
        removeAllViews();
        removeCallbacks(this);
        if (componentListItemStyleAdaptor!=null){
            componentListItemStyleAdaptor.clearEvent();
        }
        if (icmp26Holder!=null){
            icmp26Holder.removeCMP26Flag();
            icmp26Holder=null;
        }
    }


//    class MsgHandle extends Handler {
//        public MsgHandle(Looper looper) {
//            super(looper);
//        }
//
//        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            if (msg.what == 0) {
//                List<ComponentItem> componentItems = msg.getData().getParcelableArrayList("data");
//                boolean addInsert = msg.arg1 > 0;
//                showView(componentItems, addInsert);
//                if (addInsert) {
//                    Log.w(TAG, "handleMessage addInsert");
//                } else {
//                    Log.w(TAG, "handleMessage update");
//                }
//                if (!addInsert) {
//                    sendEmptyMessage(1);
//                    Log.w(TAG, "send clear all compponent msg");
//                } else {
//                    run();
//                }
//            } else if (msg.what == 1) {
//                Log.w(TAG, "clear oldContainer");
//                if (oldContainer != null) {
//                    oldContainer.removeAllViews();
//                    if (oldContainer.getParent() != null) {
//                        ((ViewGroup) oldContainer.getParent()).removeView(oldContainer);
//                    }
//                }
//                oldContainer = null;
//                // run();
//                int ChildCount = getChildCount();
//                Log.w(TAG, "clear all compponent complete ChildCount>>" + ChildCount);
//                if (ChildCount > 0) {
//                    Log.w(TAG, "child hashCode>>" + getChildAt(0).hashCode());
//                }
//            }
//        }
//    }

    @Override
    public void run() {
        if (context==null){
            return;
        }
        if (context instanceof Activity){
            if(((Activity)context).isFinishing()||((Activity)context).isDestroyed()){
                return;
            }
        }
        requestLayout();
        postInvalidate();
    }

    private int getWindowInfo(boolean isWd) {
        WindowManager wm =
                (MultiUtils.scanForActivity(getContext())).getWindowManager();

        int width = wm.getDefaultDisplay().getWidth();
        int height =
                wm.getDefaultDisplay().getHeight();

        return isWd ? width : height;
    }

    @Override
    public void addView(View child) {
        super.addView(child);
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        dispose();
    }
}